/**
 * 
 */
package com.evon.yardmanagement.ui.action;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.validation.SkipValidation;

import com.evon.yardmanagement.export.ImportDataManager;
import com.evon.yardmanagement.export.ImportableData;
import com.evon.yardmanagement.export.ParkingSlotExportableData;
import com.evon.yardmanagement.model.ParkingSlot;
import com.evon.yardmanagement.model.Section;
import com.evon.yardmanagement.model.Yard;
import com.evon.yardmanagement.service.ParkingSlotsService;
import com.evon.yardmanagement.service.SectionManagementService;
import com.evon.yardmanagement.service.YardManagementService;
import com.evon.yardmanagement.transformer.BaseTransformer;
import com.evon.yardmanagement.transformer.ParkingSlotTransfer;
import com.evon.yardmanagement.transformer.SectionTransformer;
import com.evon.yardmanagement.ui.dto.ParkingSlotDTO;
import com.evon.yardmanagement.ui.dto.SectionDTO;
import com.evon.yardmanagement.ui.dto.YardDTO;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
/**
 * @author Sandeep
 * 
 */
public class AddSectionAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public AddSectionAction() {
		listAvailblYards = new ArrayList<YardDTO>();
		listParkingSlots = new ArrayList<ParkingSlotDTO>();
		listParking = new ArrayList<ParkingSlotDTO>();
		// listAvailblYards = new ArrayList<YardDTO>();
		// parkingSlotDTO = new ParkingSlotDTO();
		sectionDTO = new SectionDTO();

		System.out.println("section id= " + getSectionId());
	}

	private List<YardDTO> listAvailblYards;
	private List<ParkingSlotDTO> listParkingSlots;
	private SectionDTO sectionDTO;
	
	private List<ParkingSlotDTO> listParking;
	
	private String hidYardId;
	
	private int yardId; 
	
	private int oemId;

	private int sectionId;

	private File parkingSlotUploadFile;
	
	private boolean isSectionNotSelected = false;
	
	private int addCounter = 1;
	public List<Yard> listYard = new ArrayList<Yard>();
	
	public boolean isSectionNotSelected() {
		return isSectionNotSelected;
	}

	
	public int getOemId() {
		return oemId;
	}

	@SkipValidation
	public void setOemId(int oemId) {
		this.oemId = oemId;
	}


	@SkipValidation
	public void setSectionNotSelected(boolean isSectionNotSelected) {
		this.isSectionNotSelected = isSectionNotSelected;
	}

	public List<ParkingSlotDTO> getListParking() {
		return listParking;
	}

	@SkipValidation
	public void setListParking(List<ParkingSlotDTO> listParking) {
		this.listParking = listParking;
	}

	public int getYardId() {
		return yardId;
	}

	@SkipValidation
	public void setYardId(int yardId) {
		this.yardId = yardId;
	}

	BaseTransformer<ParkingSlot, ParkingSlotDTO> psTransformer = new BaseTransformer<ParkingSlot, ParkingSlotDTO>(
			ParkingSlot.class, ParkingSlotDTO.class);

	public int getSectionId() {
		return sectionId;
	}

	@SkipValidation
	public void setSectionId(int sectionId) {
		this.sectionId = sectionId;
	}

	public String getHidYardId() {
		return hidYardId;
	}

	@SkipValidation
	public void setHidYardId(String hidYardId) {
		this.hidYardId = hidYardId;
	}

	// public ParkingSlotDTO parkingSlotDTO ;

	public List<ParkingSlotDTO> getListParkingSlots() {
		return listParkingSlots;
	}

	@SkipValidation
	public void setListParkingSlots(List<ParkingSlotDTO> listParkingSlots) {
		this.listParkingSlots = listParkingSlots;
	}

	public SectionDTO getSectionDTO() {
		return sectionDTO;
	}

	@SkipValidation
	public void setSectionDTO(SectionDTO sectionDTO) {
		this.sectionDTO = sectionDTO;
	}

	/*
	 * public ParkingSlotDTO getParkingSlotDTO() { return parkingSlotDTO; }
	 * 
	 * public void setParkingSlotDTO(ParkingSlotDTO parkingSlotDTO) {
	 * this.parkingSlotDTO = parkingSlotDTO; }
	 */

	public List<YardDTO> getListAvailblYards() {
		return listAvailblYards;
	}

	@SkipValidation
	public void setListAvailblYards(List<YardDTO> listAvailblYards) {
		this.listAvailblYards = listAvailblYards;
	}

	@SkipValidation	
	public String populate() {
		listYard = new YardManagementService().getAllYards();

		if (getSectionId() != 0) {
			
			SectionManagementService service = new SectionManagementService();
			List<Section> sections = service
					.getSectionBySectionId(getSectionId());
			// SectionDTO sectionDTO = null;
			for (Section section : sections) {
				sectionDTO = SectionTransformer.transformToDTO(section);

			}

			ParkingSlotsService pservice = new ParkingSlotsService();
			List<ParkingSlot> psList = pservice
					.fetchParkingSlotBySectionId(getSectionId());

			for (ParkingSlot pslot : psList) {
				listParkingSlots.add(psTransformer.transformToDTO(pslot));
			}
		}
		return "populate";
	}
	
	private boolean validateSection() {
		SectionDTO sectionDTO = getSectionDTO();
		boolean success  = true;
		if (sectionDTO.getSectionName()==null 
				|| "".equals(sectionDTO.getSectionName().trim()) ) {
			addActionMessage("Section Name cannot be left empty");
			success = false;
		}
		
		if (sectionDTO.getCapacity()==null 
				|| sectionDTO.getCapacity()==0 ) {
			addActionMessage("Slot cannot be left empty");
			success = false;
		}
		
		return success;
	}

	@Validations(requiredStrings = { @RequiredStringValidator(type = ValidatorType.FIELD, fieldName = "sectionDTO.sectionName", message = "You must enter a character name.")
			},
			regexFields = {
					//@RegexFieldValidator(fieldName="dto.zipCode", expression="^[0-9]+",message="Phone can only be numeric", type=ValidatorType.FIELD),
					//@RegexFieldValidator(fieldName="dto.zipCode", expression="^[0-9]+",message="Zip code can only be numeric", type=ValidatorType.FIELD),
					@RegexFieldValidator(fieldName ="sectionDTO.sectionName", expression = "^[a-zA-Z]+$", message = "Only Character is allowed for name."),
					@RegexFieldValidator(fieldName ="sectionDTO.capacity", expression = "^[0-9]+", message = "Slot can only be numeric")
					},
					requiredFields =
	                  {
					//@RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "keyBinDTO.keyBinNumber", message = "You must enter a value for field Key Bin Number." ),
					@RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "sectionDTO.capacity", message = "You must enter a value for field Slot.")
					}
	)
			//@RegexFieldValidator( type = ValidatorType.FIELD, fieldName ="sectionDTO.sectionName", expression = "^[a-zA-Z]+$", message = "Only Character is allowed for name.")
			//@RegexFieldValidator( type = ValidatorType.FIELD, fieldName ="sectionDTO.capacity", expression = "[0-9]", message = "Only numbers allowed for slot.")
	public String execute() throws Exception {
		isSectionNotSelected = false;
		
		/*if (!validateSection()) {
			return SUCCESS;
		};*/

		// SectionDTO sectionDto = new SectionDTO();
		// Section section =
		// SectionTransformer.transformCreateSection(sectionDto);
		/*
		 * Section section = new Section(); //section.setId(getSectionId());
		 * Yard yard = new Yard(); yard.setId(10); section.setYard(yard);
		 * section.setName(getSectionName());
		 * section.setIsPermanent(getPermanent()?"1":"0");
		 * section.setIsActive(isActive()?"1":"0");
		 * section.setCapacity(getCapacity());
		 */
		// sectionDTO = new SectionDTO();
		/*Map map = ActionContext.getContext().getSession();
		YardDTO yardDTO = (YardDTO) map.get("yard");*/
		int yardId = getYardId();
		if (yardId!=0) {
			YardDTO yardDTO = new YardDTO();
			yardDTO.setId(yardId);
			SectionManagementService service = new SectionManagementService();
			SectionDTO sectionDTO = getSectionDTO();
			sectionDTO.setYardDTO(yardDTO);
			//Section section = SectionTransformer.transformCreateSection(sectionDTO);
			int returnedSectionId = service.addSection(sectionDTO);
			if (returnedSectionId >0) {
				addActionMessage("Section information successfully added");
				getSectionDTO().setSectionId(returnedSectionId);
				if (listParkingSlots.size()==0){
					for (int i = 0; i < getSectionDTO().getCapacity(); i++) {
						listParkingSlots.add(new ParkingSlotDTO());
					}
				}

			} else {
				addActionMessage("Critical Error");
			}
		} else {
			System.out.println("yard id is null");
		}
		return SUCCESS;
	}

	public String submitParkingSlot() throws Exception {

		ParkingSlotsService service = new ParkingSlotsService();
		boolean success = service.addParkingSlots(listParkingSlots, sectionDTO.getSectionId());
		if (success){
			addActionMessage("Parking slots information successfully added");
		} else {
			addActionMessage("Critical Error");
		}
		return SUCCESS;
	}
	
	public String addParkingSlot() {
		if (sectionDTO.getCapacity()<= listParkingSlots.size()) {
			addActionMessage("Cannot add Parking Slot more then the specified capacity");
		} else {
			for (int i = 0; i < addCounter; i++) {
				listParkingSlots.add(new ParkingSlotDTO());
			}
		}
		return SUCCESS;
	}
	
	public String populateParkingSlot() {
		listParking = new ArrayList<ParkingSlotDTO>();
		int sectionId = getSectionId();
		ParkingSlotsService service = new ParkingSlotsService();
		List<ParkingSlot> psList = service.fetchParkingSlotBySectionId(sectionId);
		ParkingSlotDTO psDTO = null;
		for (ParkingSlot parkingSlot : psList) {
			psDTO = ParkingSlotTransfer.transformToDTO(parkingSlot);
			listParking.add(psDTO);
		}
		return "populate";
	}
	
	@SkipValidation
	public String executeParkingSlot() {
		try {
			ParkingSlotExportableData data = new ParkingSlotExportableData(null);
			data.setFileToImport(parkingSlotUploadFile);

			ImportDataManager<ImportableData> importManager = new ImportDataManager<ImportableData>(
					data);
			importManager.importDataFromExcel();

			new ParkingSlotsService().importParkingSlots(data.getData());
			System.err.println("tEsts---"
					+ this.parkingSlotUploadFile.getName());
			addActionMessage("Imported Successfully");
			// String filePath = servletRequest.getSession().getServletContext()
			// .getRealPath("/");
			// System.out.println("Server path:" + filePath);
			// File fileToCreate = new File(filePath, this.userImageFileName);
			// FileUtils.copyFile(this.userImage, fileToCreate);
			populateParkingSlot();

		} catch (Exception e) {
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	public File getParkingSlotUploadFile() {
		return parkingSlotUploadFile;
	}

	@SkipValidation
	public void setParkingSlotUploadFile(File parkingSlotUploadFile) {
		this.parkingSlotUploadFile = parkingSlotUploadFile;
	}
	
	

}
